<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="版本号" prop="versionId">
        <el-select v-model="queryParams.versionId" clearable filterable placeholder="请选择版本号">
            <el-option
             v-for="item in allVersion.filter(f=>f.productId == productId)"
              :key="item.id"
              :label="item.versionId"
              :value="item.id"
            ></el-option>
          </el-select>
        <!-- <el-input
          v-model="queryParams.versionId"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
      </el-form-item>

      <el-form-item label="发布时间" prop="rangeTime">
        <el-date-picker
          v-model="queryParams.rangeTime"
          type="monthrange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:versionManage:add']"
          >新增</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="版本号" align="center" prop="versionId" />
      <el-table-column label="说明" align="center" prop="versionDesc" />
      <el-table-column label="发布时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d}  {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="修改时间" align="center" prop="modifyTime" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:versionManage:edit']"
            >修改</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExport(scope.row)"
            v-hasPermi="['device:versionManage:download']"
            >下载</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:video:del']"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备版本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="版本号" prop="versionId">
          <el-input v-model="form.versionId" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="版本说明" prop="versionDesc">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.versionDesc"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="版本" prop="uploadVersion">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            :file-list="form.files"
            :limit="1"
            :auto-upload="false"
            :accept="fileType"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选择文件</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listVersionManage,
  delVersion,
  addVersion,
  getAllVersion
} from "@/api/device/versionManage";
import { MessageBox } from 'element-ui'
import { delVideoTutorial } from '@/api/device/videoTutorial'

export default {
  name: "Version",
  props: {
    productId: {
      type: String,
    },
    //文件类型
    fileType: {
      type: String,
    },
  },
  dicts: ["official_article_tab", 'mc_product_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: Number(this.productId), //1安卓 2Arm
        rangeTime: null,
        beginTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      //表格数据
      list: [],
      // 表单校验
      rules: {
        versionId: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
        ],
        versionDesc: [
          { required: true, message: "版本说明不能为空", trigger: "blur" },
        ],
        uploadVersion: [
          { required: true, message: "版本不能为空", trigger: "blur" },
        ],
      },
      allVersion:[],
      baseURL: process.env.VUE_APP_DOWNLOAD_API,
    };
  },
  created() {
    this.getList();
    this.getAllVersion();
    console.log("kakakaka")
  },
  methods: {
    getAllVersion(){
      getAllVersion().then(res=>{
        this.allVersion = res.data
      })
    },
    /** 查询设备版本列表 */
    getList() {
      if (this.queryParams.rangeTime) {
        this.queryParams.beginTime = this.queryParams.rangeTime[0];
        this.queryParams.endTime = this.queryParams.rangeTime[1];
      }
      this.loading = true;
      listVersionManage(this.queryParams).then((response) => {

        this.list = response.rows.slice().reverse();
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        versionId: null,
        versionDesc: null,
        productId: this.productId,
        files: [],
        uploadVersion: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加版本";
    },
    //删除视频教程
    handleDelete(row){
      MessageBox.confirm('此操作将永久删除该文件，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delVersion({id:row.id}).then((res)=>{
          if(res.code == 200 ){
            this.$modal.msgSuccess("删除成功");
            this.getVideoTutorial()
          }
        })
      }).catch(() => {
        // 用户点击“取消”
        console.log("已取消");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.uploadVersion = this.$refs.upload.uploadFiles[0]
        ? this.$refs.upload.uploadFiles[0].raw
        : null;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("uploadVersion", this.form.uploadVersion);
          formData.append("productId", this.form.productId);
          formData.append("versionId", this.form.versionId);
          formData.append("versionDesc", this.form.versionDesc);
          addVersion(formData).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 导出按钮操作 */
    handleExport(row) {
      const a = document.createElement('a') // 创建一个<a></a>标签
      a.href = this.baseURL + '/app/' + row.uploadUrl            //重点（如测试发现下载文件不存在/找不到，检查路径）
      a.download = 'UnKnow.exe'         // 设置下载文件文件名
      a.download = this.dict.type.mc_product_type.find(v => v.value == row.productId).label + "Setup.exe"
      a.style.display = 'none'           // 隐藏a标签
      document.body.appendChild(a)       // 将a标签追加到文档对象中
      a.click()                          // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove()
    },
  },
};
</script>
<style scoped></style>
